package com.hccl.mongoEntities.step;

import DM.StateMachine;
import com.hccl.mongoEntities.action.Action;
import exception.NoMatchConditionException;
import jdk.nashorn.internal.ir.annotations.Ignore;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xjzhang on 2017/11/23.
 */
public class CommandASRStep extends ASRStep{

    private List<String> commandList = new ArrayList<>();

    @Ignore
    private String matchedCommand = "";

    @Override
    public void onExit(StateMachine stateMachine){
//        logger.info(name+"step结束执行");
        stateMachine.setCurrentStep(null);
        matchedCommand = "";
    }

    @Override
    public void run(StateMachine stateMachine) throws Exception{
        try {
            onEnter(stateMachine);
            if (matchedCommand.isEmpty()){
                interrupt(stateMachine);
                run(stateMachine);
            }
            else {
                //绑定变量
                stateMachine.getBindings().put("command", matchedCommand);
                //根据condition跳转
                List<Action> actions = null;
                if (transitions.size() != 0){
                    for (StepTransition transition : transitions){
                        if ((boolean)stateMachine.getJsEngine().eval(transition.getCondition(),stateMachine.getBindings())){
                            actions = transition.getActions();
                            break;
                        }
                    }
                    if (actions == null){
//                        logger.info(commandList.toString());
                        throw new NoMatchConditionException();
                    }
                    //执行action
                    for (Action action : actions)
                        action.run(stateMachine);
                }
            }
        }finally {
            onExit(stateMachine);
        }

    }


    public List<String> getCommandList() {
        return commandList;
    }

    public void setCommandList(List<String> commandList) {
        this.commandList = commandList;
    }

    public String getMatchedCommand() {
        return matchedCommand;
    }

    public void setMatchedCommand(String matchedCommand) {
        this.matchedCommand = matchedCommand;
    }
}
